<?php

App::uses('CakeEmail', 'Network/Email');

class Ticket extends AppModel {

    public $label = "Tickets";
    public $tablePrefix = 'sop_';
    public $belongsTo = array('Admin.User', 'Empresa', 'Delegacion', 'Inventario', 'Problema');
    public $hasMany = array('TicketEvento');
    public $validate = array(
        'user_id' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'El nombre del cliente es requerido'
            )
        ),
        'problema_id' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'El problema del ticket es requerido'
            )
        ),
        'estado' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'El estado del ticket es requerido'
            )
        ),
        'descripcion' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'La descripción del ticket es requerida'
            )
        ),
        'tmp_observacion' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'La observación de la edición es requerida'
            )
        )
    );

    public function isOwnedBy($ticket, $user) {
        return $this->field('id', array('id' => $ticket, 'user_id' => $user)) === $ticket;
    }
    
    public function afterSave($created) {         
        $data = array(
            'fecha_carga' => date("Y-m-d H:i:s"),
            'ticket_id' =>  $this->id,
            'user_id' => AuthComponent::user('id'),
            'estado' => $this->data['Ticket']['estado'],
            'observacion' => isset($this->data['Ticket']['tmp_observacion']) ? $this->data['Ticket']['tmp_observacion'] : ''
        );

        $this->TicketEvento->create();
        $this->TicketEvento->save($data);
    }

}